var express = require('express');
var router = express.Router();
const model = require('../model')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 注册接口
router.post('/regist',function(req,res,next){
  const data = {
    username:req.body.username,
    password1:req.body.password1,
    password2:req.body.password2
  }
  model.connect(function(db){
    db.collection('users').insertOne(data,function(err,ret){
      if(err){
        console.log('注册失败')
        res.redirect('/regist');
      }else{
        console.log('注册成功')
        res.redirect('/login');
      }
    })
  })
})
// 登陆接口
router.post('/login',function(req,res,next){
  const data = {
    username:req.body.username,
    password1:req.body.password1
  }
  model.connect(function(db){
    db.collection('users').find(data).toArray(function(err,da){
      if(err){
        console.log('注册失败')
        res.redirect('/login');
      }else{
        if(da.length > 0){
          res.redirect('/')
        }else{
          res.redirect('/login')
        }
      }
    })
  })
})

module.exports = router;
